package com.example.androidencryption;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidencryption.databinding.ActivityRsaBinding;
import com.example.androidencryption.utils.ConvectionUtils;
import com.example.androidencryption.utils.RSAUtils;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

public class RSAActivity extends AppCompatActivity {
    private static final String TAG  = "RSAActivity";

    private   KeyPair keyPair;
    private   String publicKeyStr;
    private   String privateKeyStr;

    private final String  dataStr = "Hello World!";

    private byte[] encryptArray;

            ActivityRsaBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRsaBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.genKeyPairBtn.setOnClickListener(v -> keyPair = RSAUtils.genKeyPair());

        binding.getPublicKeyBtn.setOnClickListener(v -> {
            if (keyPair != null){
                PublicKey publicKey = RSAUtils.getPublicKey(keyPair);
                publicKeyStr =  RSAUtils.getHexStrPublicKey(publicKey);
                Log.i(TAG, "getPublicKeyBtn: " + publicKeyStr);
            }

        });

        binding.getPriveteBtn.setOnClickListener(v -> {
            if (keyPair != null){
                PrivateKey privateKey = RSAUtils.getPrivateKey(keyPair);
                privateKeyStr =  RSAUtils.getHexStrPrivateKey(privateKey);
                Log.i(TAG, "getPriveteBtn: " + privateKeyStr);
            }
        });

        binding.encodeBtn.setOnClickListener(v -> {
            PublicKey publicKey = RSAUtils.loadPublicKey(publicKeyStr);
            if (publicKey != null){
                Log.i(TAG, "encrypt data: " + dataStr);
                 encryptArray =  RSAUtils.encrypt(publicKey,dataStr.getBytes(StandardCharsets.UTF_8));
                 Log.i(TAG, "encrypt: " + ConvectionUtils.byte2HexStr(encryptArray));
            }

        });

        binding.decodeBtn.setOnClickListener(v -> {
            PrivateKey privateKey = RSAUtils.loadPrivateKey(privateKeyStr);
            if (privateKey != null){
               byte[]  decryptArray =  RSAUtils.decrypt(privateKey,encryptArray);
                Log.i(TAG, "decrypt data: " + new String(decryptArray,StandardCharsets.UTF_8));
            }
        });

    }

}